package demos;

import java.util.concurrent.*;

class Counter implements Runnable {
	protected CountDownLatch latch;
	protected static int count = 0;
	
	public Counter(CountDownLatch latch) {
		this.latch = latch;
	}
	
	@Override
	public void run() {
		count++;
		latch.countDown();
	}
}

class EndCounter extends Counter {

	public EndCounter(CountDownLatch latch) {
		super(latch);
	}
	
	@Override
	public void run() {
		super.run();
		try {
			latch.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(count);
	}
}
public class CountDownLatchTest {
	
	public static void main(String[] args) {
		CountDownLatch latch = new CountDownLatch(5);
		ExecutorService exec = Executors.newCachedThreadPool();
		exec.execute(new EndCounter(latch));
		for(int i = 0; i < 4; i++) 
			exec.execute(new Counter(latch));
	}
	
}
